var options = {
    settings: {},

    //当用户每次打开配置页时，需要通过setting来填充保存的数据
    loadSettings() {
        // 与backgroung通信
        let info = chrome.extension.getBackgroundPage();
        let version = info.backgroundInfo.version;
        document.getElementById("optionsTitle").innerHTML = "原神日报&nbsp;&nbsp;" + "<span style='color: #1E9FFF'>Version&nbsp;" + version + "</span>";
        //根据setting设置当前刷新频率
        var obj = document.getElementById("refreshFreq");
        for (i = 0; i < obj.length; i++) {
            if (obj[i].value == this.settings.refreshFrequency / 1000)
                obj[i].selected = true;
        }
        //刷新select选择框渲染
        layui.use('form', function () {
            var form = layui.form;
            form.render("select");

            //数据源开关检测
            //bili数据源
            if (options.settings.biliChecked == true)
                document.getElementById("biliSwitch").checked = true;
            else
                document.getElementById("biliSwitch").checked = false;
            //weibo
            if (options.settings.weiboChecked == true)
                document.getElementById("weiboSwitch").checked = true;
            else
                document.getElementById("weiboSwitch").checked = false;
            //刷新复选框渲染
            form.render("checkbox");
        });
    },


    //保存用户设置
    saveSettings() {
        document.getElementById("submitOptions").addEventListener('click',
            () => {
                let refreshFrequency = document.getElementById("refreshFreq").value * 1000;

                options.settings.refreshFrequency = refreshFrequency;
                options.settings.biliChecked = document.getElementById("biliSwitch").checked;
                options.settings.weiboChecked = document.getElementById("weiboSwitch").checked;
                //保存数据
                chrome.storage.local.set({
                    settings: options.settings,
                }, function () {
                    //解除旧循环，建立新循环
                    let info = chrome.extension.getBackgroundPage();
                    // info.clearInterval(info.extension.setIntervalId);
                    clearInterval(info.backgroundInfo.setIntervalId);
                    info.backgroundInfo.SetInterval(refreshFrequency);
                    //更新 background.js 中的settings数据
                    info.backgroundInfo.settings = options.settings;
                    info.backgroundInfo.getAllDynamic();
                    layui.use('layer', function () {
                        var layer = layui.layer;
                        layer.msg("保存成功", { time: 2000 });
                    });
                });
            });

    }
}

window.onload = function () {
    chrome.storage.local.get(["settings"], result => {
        options.settings = result.settings;
        options.loadSettings();
        options.saveSettings();
    });
}
